package com.lzh.chatnote.user.service.event.listener;

import com.lzh.chatnote.user.dao.UserDao;
import com.lzh.chatnote.user.domain.entity.User;
import com.lzh.chatnote.user.domain.enums.UserOnlineStatusEnum;
import com.lzh.chatnote.user.service.IpQueryServiceImpl;
import com.lzh.chatnote.user.service.cache.UserOnlineCache;
import com.lzh.chatnote.user.service.event.UserOnlineEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Slf4j
@Component
public class UserOnlineListener {

    @Resource
    private UserDao userDao;
    @Resource
    private IpQueryServiceImpl ipQueryServiceImpl;
    @Resource
    private UserOnlineCache userOnlineCache;


    //添加用户上线列表到redis
    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void addOnlineUserList(UserOnlineEvent event) {
        log.info("用户上线：{}", event.getUser());
        userOnlineCache.online(event.getUser().getId(),LocalDateTime.now());
    }

    //解析用户ip信息
    @Async
    @EventListener(classes = UserOnlineEvent.class)
    public void parseIpInfo(UserOnlineEvent event) {
        log.info("用户注册：{}", event.getUser());
        User currentUser = event.getUser();
        currentUser.setUpdateTime(LocalDateTime.now());
        currentUser.setLastOptTime(LocalDateTime.now());
        currentUser.setStatus(UserOnlineStatusEnum.ONLINE.getType());
        userDao.updateById(currentUser);
        //获取或者刷新ip信息
        ipQueryServiceImpl.refreshIpDetail(currentUser.getId());


    }

}
